package com.example.kotlintest.ui

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.paging.PagingDataAdapter
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.RecyclerView
import com.example.kotlintest.bean.TouTiaoData
import com.example.kotlintest.databinding.ItemNewsListBinding

class TouTiaoAdapter : PagingDataAdapter<TouTiaoData.Result.Data, TouTiaoAdapter.TouTiaoViewHolder>
    (TouTiaoDiffCallback()) {


    override fun onBindViewHolder(holder: TouTiaoViewHolder, position: Int) {
        val newsData = getItem(position)
        if (newsData != null) {
            newsData.id = position.toString()
            holder.bind(newsData)
        }
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TouTiaoViewHolder {
        return TouTiaoViewHolder(
            ItemNewsListBinding.inflate(
                LayoutInflater.from(parent.context),
                parent,
                false
            )
        )
    }

    class TouTiaoViewHolder(val binding: ItemNewsListBinding) :
        RecyclerView.ViewHolder(binding.root) {
        fun bind(item: TouTiaoData.Result.Data) {
            binding.apply {
                newsData = item
                executePendingBindings()
            }
        }
    }

    private class TouTiaoDiffCallback : DiffUtil.ItemCallback<TouTiaoData.Result.Data>() {
        override fun areItemsTheSame(
            oldItem: TouTiaoData.Result.Data,
            newItem: TouTiaoData.Result.Data
        ): Boolean {
            return oldItem.uniquekey == newItem.uniquekey
        }

        override fun areContentsTheSame(
            oldItem: TouTiaoData.Result.Data,
            newItem: TouTiaoData.Result.Data
        ): Boolean {
            return oldItem == newItem
        }
    }
}